<?php
session_start();
require_once 'conn.php';

// 确保用户已经登录
if (!isset($_SESSION['user_id'])) {
    echo "<script>alert('请先登录'); window.location.href = 'login.php';</script>";
    exit();
}

$user_id = $_SESSION['user_id'];  // 当前登录用户ID

// 检查表单数据是否提交
if (isset($_POST['current_password']) && isset($_POST['new_password']) && isset($_POST['confirm_password'])) {
    // 获取当前密码、新密码和确认密码
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    // 验证新密码与确认密码是否一致
    if ($new_password !== $confirm_password) {
        echo "<script>alert('新密码与确认密码不一致，请重新输入。'); window.history.back();</script>";
        exit();
    }

    // 从数据库获取当前用户的存储密码（无加密）
    $sql = "SELECT password FROM users WHERE id = $user_id";
    $result = mysqli_query($conn, $sql);

    // 如果用户存在
    if ($result && mysqli_num_rows($result) > 0) {
        $user = mysqli_fetch_assoc($result);

        // 检查当前密码是否正确
        if ($user['password'] === $current_password) {
            // 当前密码正确，更新为新密码
            $update_sql = "UPDATE users SET password = '$new_password' WHERE id = $user_id";
            if (mysqli_query($conn, $update_sql)) {
                echo "<script>alert('密码修改成功!'); window.location.href = 'profile.php';</script>";
            } else {
                echo "<script>alert('密码更新失败，请稍后再试。'); window.history.back();</script>";
            }
        } else {
            echo "<script>alert('当前密码不正确，请重新输入。'); window.history.back();</script>";
        }
    } else {
        echo "<script>alert('未找到该用户信息，请重试。'); window.history.back();</script>";
    }
} else {
    echo "<script>alert('请填写所有必填字段。'); window.history.back();</script>";
}
?>
